package net.hiapoe.gsnake4j.bean;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.text.SimpleDateFormat;
import java.util.Random;

import net.hiapoe.gsnake4j.window.RunMe;
/**
 * 
 * @Author Administrator
 * @Description 负责重绘
 * @Version 1.0.3
 * @Date 2013年10月1日
 */
public class Drawer implements Runnable {
	// 常量
	public final static Color DEFAULT_CANVAS_COLOR = Color.BLACK;
	public final static Color DEFAULT_SNAKE_COLOR = new Color(255, 255, 255, 180)
	.brighter();
	public final static Random RANDOMer = new Random();
	public final static int CANVAS_WIDTH = 439;
	public final static int CANVAS_HEIGHT = 329;
	public final static int NODE_WIDTH = 10;
	public final static int NODE_HEIGHT = 10;
	public final static int MAX_NODE_NUM_X = (CANVAS_WIDTH + 1)
			/ (NODE_WIDTH + 1);
	public final static int MAX_NODE_NUM_Y = (CANVAS_HEIGHT + 1)
			/ (NODE_HEIGHT + 1);

	/*
	 * run方法
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		while (true) {
			reFresh();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/*
	 *  单线程调用, 刷新界面
	 */
	public static void reFresh() {
		Graphics g = RunMe.window.canvas.getGraphics();
		long runtime = Snake.getInstance().getRuntime();
		String formatedtime = (new SimpleDateFormat("mm分ss秒")).format(runtime);
		RunMe.window.jlabel.setText("  第" + Snake.getInstance().getTimes()
				+ "局            你的得分: " + Snake.getInstance().getPoint()
				+ "           本局时间: " + formatedtime);
		// 可能会造成Snake的闪烁
		if(!g.drawImage(Toolkit.getDefaultToolkit()
				.getImage("./img/background.jpg"), 0, 0, CANVAS_WIDTH,
				CANVAS_HEIGHT, null)){
			//解决图片未加载成功时画布未清空的问题
			g.setColor(Color.BLACK);
			
			g.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		}
		g.setColor(DEFAULT_SNAKE_COLOR);
		synchronized (Snake.SNAKE_LOCKER) {
			for (Node node : Snake.getInstance().getNodes()) {
				g.fillRect(getPointByNode(node)[0], getPointByNode(node)[1],
						NODE_WIDTH, NODE_HEIGHT);
			}
		}
		g.setColor(getChangingFoodcolor());
		g.fillRect(getPointByNode(Snake.getCurrentfood())[0],
				getPointByNode(Snake.getCurrentfood())[1], NODE_WIDTH, NODE_HEIGHT);

	}
	/*
	 * 得到Node左上角顶点坐标
	 */
	private static int[] getPointByNode(Node node) {
		int[] re = new int[2];
		re[0] = (node.getX() - 1) * (NODE_WIDTH + 1);
		re[1] = (node.getY() - 1) * (NODE_HEIGHT + 1);
		return re;
	}
	/*
	 * 得到随机颜色
	 */
	public static Color getChangingFoodcolor() {
		return new Color(RANDOMer.nextInt(16) * 16, RANDOMer.nextInt(16) * 16,
				RANDOMer.nextInt(16) * 16, RANDOMer.nextInt(16) * 16).brighter();
	}
	
	
}
